<template>
	<div class="user-content">
		<el-form :inline="true" :model="searchForm" class="search">
			<el-form-item label="角色名">
				<el-input v-model="searchForm.roleName" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="queryRoleListByPage()">查询</el-button>
				<el-button type="primary" @click="addUpdateRole(null)">新增</el-button>
				<el-button type="primary" @click="deleteRoleList">删除</el-button>
			</el-form-item>
		</el-form>
		<div class="table">
			<el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column fixed prop="roleName" label="角色名称">
				</el-table-column>
				<el-table-column prop="description" label="描述">
				</el-table-column>
				<el-table-column prop="activeFlag" label="激活标识">
				</el-table-column>
				<el-table-column fixed="right" label="操作">
					<template slot-scope="scope">
						<el-button type="text" @click="addUpdateUser(scope.row)" @refresh="refreshPage">编辑</el-button>
						<el-button type="text" @click="allotPermission(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
			:page-sizes="[10,50, 100, 200, 500, 1000]" :page-size="pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagina">
		</el-pagination>
		<RoleSaveUpdateVue ref="child" @refresh="refreshPage"></RoleSaveUpdateVue>
		
		<el-dialog :title="permissionTreeTitle" :visible.sync="permissionDialogvisible" :before-close="closePermTree" >
			<el-tree ref="permTree" :data="treeData" show-checkbox node-key="id" :props="defaultProps">
			</el-tree>
			<el-button type="primary" @click="saveRolePermissions">确定</el-button>
		</el-dialog>
	</div>
</template>

<script>
	import {
		Message
	} from 'element-ui';
	import {
		queryRolesByPage,
		deleteRoles,
		getPermissionTree,
		saveRolePermission,
		queryAllotedPer
	} from './api';
	import RoleSaveUpdateVue from './RoleSaveUpdate.vue';
	import Qs from 'qs';
	export default {
		components: {
			RoleSaveUpdateVue,
		},
		data() {
			return {
				tableData: [],
				searchForm: {
					roleName: '',
				},
				currentPage: 1,
				pageSize: 10,
				total: 0,
				childData: {
					visible: false,
					title: '',
					userForm: {}
				},
				multipleSelection: [],
				permissionDialogvisible: false,
				treeData: [],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				permissionTreeTitle: "分配角色",
				allotRoleId: '', //分配角色ID
			}
		},
		mounted() {
			this.queryRoleListByPage();
			this.queryPermissionTreeList();
		},
		methods: {
			// handleClick(row) {
			// 	console.log(row);
			// },
			handleSizeChange(val) {
				this.pageSize = val
				this.queryRoleListByPage();
				// console.log(`每页 ${val} 条`);
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.queryRoleListByPage();
				// console.log(`当前页: ${val}`);
			},
			queryRoleListByPage() {
				let params = {
					page: this.currentPage,
					pageSize: this.pageSize,
					rolename: this.searchForm.roleName,
				}
				queryRolesByPage(params).then(res => {
					// console.log(res.data);
					if (res.data.code == 0) {
						this.total = res.data.data.total;
						this.tableData = res.data.data.list;
					} else {
						Message.error(res.data.msg);
					}
				})
			},
			addUpdateRole(param) {
				if(param != null) {
					this.childData.title = '编辑';
					this.childData.userForm = param;
				}else{
					this.childData.title = '新增';
					this.childData.userForm = null;
				}
				this.childData.visible = true;
				const child = this.$refs.child;
				if (child) {
					child.receiveValues(this.childData);
				}
			},
			refreshPage(){
				this.queryRoleListByPage();
			},
			deleteRoleList(){
				// console.log(this.multipleSelection);
				if(this.multipleSelection.length == 0){
					Message({
						showClose: true,
						message: '请选择数据进行删除！',
						duration: 3000,
						type: 'warning'
					})
				}
				const ids = [];
				this.multipleSelection.forEach(item => {
					ids.push(item.id)
				})
				deleteUsers(ids).then(res => {
					if(res.data.code == 0){
						//刷新页面
						this.queryRoleListByPage();
						Message({
							showClose: true,
							message: '删除成功',
							type: 'success'
						})
					}else{
						Message.error(res.data.msg);
					}
				})
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			allotPermission(row){
				this.allotRoleId = row.id;
				//查询已配置的权限
				//发送请求请求后台
				queryAllotedPer(this.allotRoleId).then(res => {
					if(res.data.code == 0){
						console.log(res.data.data)
						//配置选中的权限
						this.$refs.permTree.setCheckedKeys(res.data.data);
					}
				})
				this.permissionTreeTitle = "请为"+row.roleName+"分配角色";
				this.permissionDialogvisible = true;
			},
			queryPermissionTreeList() {
				getPermissionTree().then(res => {
					if (res.data.code == 0) {
						this.treeData = res.data.data;
					}
				})
			},
			saveRolePermissions() {
				debugger;
				if (this.allotRoleId == '' || this.allotRoleId == null) {
					Message({
						type: 'warning',
						message: '未获取到角色Id，请重新分配权限',
						showClose: true,
						duration: 3000
					})
					return;
				}
				const checkRoles = this.$refs.permTree.getCheckedNodes();
				const permissionIds = []
				checkRoles.forEach(item => {
					permissionIds.push(item.id);
				})
				//发送请求保存用户角色信息
				let data = {
					'roleId': this.allotRoleId,
					'permissionIds': JSON.stringify(permissionIds),
				}
				saveRolePermission(data).then(res => {
					if (res.data.code == 0) {
						this.$refs.permTree.setCheckedKeys([]);
						Message({
							type: 'success',
							message: '保存成功',
							duration: 3000,
						})
					} else {
						Message.error(res.data.msg);
					}
				})
			},
			closePermTree(){
				this.$refs.permTree.setCheckedKeys([]);
				this.permissionDialogvisible = false;
			}
		},
	}
</script>

<style>
	.user-content {
		height: 100vh;
		background-color: white;
	}

	.table {
		margin: 5px;
	}

	.search {
		margin: 5px;
		float: left;
	}

	.pagina {
		float: right;
		margin-right: 10%;
	}
</style>